﻿#region Copyrights Notice
//©2009 Microsoft Corporation.  All rights reserved.
#endregion

using System;
using System.Collections;
using System.Data;
using System.DirectoryServices;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.RegularExpressions;
using System.Text.RegularExpressions;
using Microsoft.CISG.BitlockerRecovery.CDE;
using Microsoft.CISG.BitlockerRecovery.DL;
[assembly: CLSCompliant(true)]


namespace Microsoft.CISG.BitlockerRecovery.BL
{
    public static class CommonBL
    {
        [DirectoryServicesPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
        public static IdentityCDE SearchGUID(string guid, string requestor, string requestedfor, int roleId)
        {
            IdentityCDE RequestedforInfo = new IdentityCDE();

            RequestedforInfo = CommonDL.SearchGUID(guid, requestor, requestedfor, roleId);

            char[] StrSeperator = new char[] { '\\' };
            string[] aryAuthUser = requestedfor.Split(StrSeperator);

            string Domain = aryAuthUser[0];
            RequestedforInfo.UserDomain = Domain;
            string CNName = "sAMAccountName=" + aryAuthUser[1];

            string UserMngr = ActiveDirectoryLookup(Domain, CNName, "manager");
            RequestedforInfo.UserManagerAlias = ActiveDirectoryLookup(Domain, "distinguishedName=" + UserMngr, "mailNickname");


            return RequestedforInfo;
        }
        public static DataSet Search(string searchValue, string requestor, string requestedfor, int roleId)
        {
            return CommonDL.Search(searchValue, requestor, requestedfor, roleId);
        }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]//this returns a dataset and should not be made into a property
        public static DataSet GetFaq()
        {
            return CommonDL.GetFaqQuestions();
        }
        [DirectoryServicesPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
        public static IdentityCDE GetUserADData(string authUser)
        {
            char[] StrSeperator = new char[] { '\\' };
            string[] aryAuthUser = authUser.Split(StrSeperator);

            string Domain = aryAuthUser[0];

            string CNName = "sAMAccountName=" + aryAuthUser[1];
            IdentityCDE UserData = new IdentityCDE();
            UserData.UserDomain = Domain;
            UserData.UserAlias = CommonBL.ActiveDirectoryLookup(Domain, CNName, "sAMAccountName");
            UserData.MemberOf = CommonBL.ActiveDirectoryLookupAry(Domain, CNName, "memberOf");
            string UserMngr = CommonBL.ActiveDirectoryLookup(Domain, CNName, "manager");
            UserData.UserManagerAlias = CommonBL.ActiveDirectoryLookup(Domain, "distinguishedName=" + UserMngr, "mailNickname");

            return UserData;
        }
        [DirectoryServicesPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
        public static string ActiveDirectoryLookup(string domain, string filter, string activeDirectoryProperty)
        {
            string ReturnValue = null;
            string LDAPConnectionPath = "LDAP://" + domain;

            DirectoryEntry ent = new DirectoryEntry(LDAPConnectionPath);
            ent.RefreshCache();

            DirectorySearcher search = new DirectorySearcher(ent);
            search.SearchScope = SearchScope.Subtree;
            search.Filter = filter;

            search.PropertiesToLoad.Add(activeDirectoryProperty);

            SearchResult result = search.FindOne();

            if (result != null)
            {
                ReturnValue = result.Properties[activeDirectoryProperty][0].ToString();
            }

            search.Dispose();
            ent.Close();
            return ReturnValue;

        }
        [DirectoryServicesPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
        private static string ActiveDirectoryLookupAry(string domain, string filter, string activeDirectoryProperty)
        {
            string LDAPConnectionPath = "LDAP://" + domain;
            StringBuilder arrayValues = new StringBuilder();

            DirectoryEntry ent = new DirectoryEntry(LDAPConnectionPath);
            ent.RefreshCache();

            DirectorySearcher search = new DirectorySearcher(ent);
            search.SearchScope = SearchScope.Subtree;
            search.Filter = filter;

            search.PropertiesToLoad.Add(activeDirectoryProperty);

            SearchResult result = search.FindOne();
            int propertyCount = result.Properties[activeDirectoryProperty].Count;

            String dn;
            int equalsIndex, commaIndex;

            for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
            {
                dn = (String)result.Properties[activeDirectoryProperty][propertyCounter];

                equalsIndex = dn.IndexOf("=", 1, StringComparison.Ordinal);
                commaIndex = dn.IndexOf(",", 1, StringComparison.Ordinal);
                if (-1 == equalsIndex)
                {
                    return null;
                }
                arrayValues.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                arrayValues.Append("|");
            }

            search.Dispose();
            ent.Close();
            return arrayValues.ToString();

        }
        [DirectoryServicesPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
        public static int ActiveDirectoryPropertyGroupLookup(int roleId)
        {
            int returnvalue = 0;

            string AppGroup = CommonDL.GetAppRoleGroup(roleId);

            string AuthUser = HttpContext.Current.User.Identity.Name.ToLower(CultureInfo.CurrentCulture);
            IdentityCDE UserInfo = new IdentityCDE();
            UserInfo = GetUserADData(AuthUser);

            if (UserInfo.MemberOf.Contains(AppGroup) == true)
            {
                returnvalue = roleId;
            }
            else
            {
                returnvalue = 1;
            }


            return returnvalue;
        }
        public static void InsertFaq(int sortOrder, string faqText)
        {
            CommonDL.InsertFaq(sortOrder, faqText);
        }
        public static void DeleteFaq(int faqId)
        {
            CommonDL.DeleteFaq(faqId);
        }
        public static void UpdateFaq(int faqId, int sortOrder, string faqDescription)
        {
            CommonDL.UpdateFaq(faqId, sortOrder, faqDescription);
        }
        public static string GenerateTpmxml(string tpmHash)
        {
            string Tpmxml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
            Tpmxml = Tpmxml + "<!--";
            Tpmxml = Tpmxml + "This page is a backup of TPM (Trusted Platform Module) owner ";
            Tpmxml = Tpmxml + "authorization information. Upon request, use the authorization information to ";
            Tpmxml = Tpmxml + "prove ownership of the computer's TPM. ";
            Tpmxml = Tpmxml + "Please keep this file in a secure location away from your computer's local hard drive. ";
            Tpmxml = Tpmxml + "--> ";
            Tpmxml = Tpmxml + "<tpmOwnerData> ";
            Tpmxml = Tpmxml + "<ownerAuth>" + tpmHash + "</ownerAuth> ";
            Tpmxml = Tpmxml + "</tpmOwnerData> ";

            return Tpmxml;
        }
        public static string GetConfigValue(string configName)
        {
            return CommonDL.GetConfigValue(configName);
        }
        public static void UpdateConfigValue(string configName, string configValue)
        {
            CommonDL.UpdateConfigValue(configName, configValue);
        }
        public static DataSet GetSummaryReport(DateTime startDate, DateTime endDate)
        {

            return CommonDL.GetSummaryReport(startDate.AddDays(-1), endDate.AddDays(1));
        }
        public static DataSet GetDetailReport(DateTime startDate, DateTime endDate)
        {
            return CommonDL.GetDetailReport(startDate.AddDays(-1), endDate.AddDays(1));
        }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]//this returns a dataset and should not be made a property
        public static DataSet GetEmailTemplateList()
        {
            return CommonDL.GetEmailTemplateList();
        }
        public static void UpdateEmailTemplate(int notificationId, string from, string subject, string message)
        {
            CommonDL.UpdateEmailTemplate(notificationId, from, subject, message);
        }
    }
}
